﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class CameraMap : MonoBehaviour
{
    [System.Serializable]
    public struct LevelConfig
    {
        [System.NonSerialized]
        public string levelName;
        public Vector2 PlayerFlagPosition;
        public Vector2 BrideyeMapPosition;
        public Vector2 BrideyePlayerFlagPosition;
        public float scrollBackLeftLimit;
        public int showUnderGroundIndex;
    }

    [Header("调试配置")]
    [Tooltip("开启调试")]
    public bool debug = false;
    [Tooltip("设置显示的关卡号")]
    [Range(1, 8)]
    public int debugLevel = 1;

    [Header("基础配置")]
    [Tooltip("摄像头移动速度")]
    public float cameraMoveSpeed = 3f;
    [Tooltip("摄像头左边界x值")]
    public float cameraLeftEdge = 8f;
    [Tooltip("摄像头右边界x值")]
    public float cameraRightEdge = 8f + 9f;
    [Tooltip("摄像头移动动作定义")]
    public SeqAction cameraMoveAction = new() { beginWaitTime = 0.5f };
    [Tooltip("摄像头当前移动方向")]
    private Vector3 cameraMoveDirection = Vector3.right;

    [Header("音乐配置")]
    public AudioSource warningSound;
    public AudioSource brideyeScrollSound;
    public AudioSource playerFlagTickSound;

    [Header("玩家位置标记及附加地图配置")]
    [Tooltip("玩家位置标记闪烁使用的精灵")]
    public Sprite[] playerFlagSptites;
    [Tooltip("玩家位置标记闪烁动作定义")]
    public SeqAction playerFlagFlashAction = new() { beginWaitTime = 0f, intervalTime = 0.1f, keepingTime = 3f };
    [Tooltip("附加地下通道地图的对象")]
    public GameObject[] underGroundObjects;
    [Tooltip("玩家位置标记对象")]
    private GameObject playerFlagObject;

    [Header("鸟瞰地图配置")]
    [Tooltip("鸟瞰地图的展开速度")]
    public float brideyeMapScrollSpeed = 8 / 16 * Utility.FramePreSecond;
    [Tooltip("鸟瞰地图展开动作定义")]
    public SeqAction brideyeMapScrollAction = new() { beginWaitTime = 38 / Utility.FramePreSecond, intervalTime = 0f };
    [Tooltip("鸟瞰地图中玩家位置标记闪烁使用的精灵")]
    public Sprite[] brideyePlayerFlagSptites;
    [Tooltip("鸟瞰地图中玩家位置标记闪烁动作定义")]
    public SeqAction brideyePlayerFlagFlashAction = new() { beginWaitTime = 0f, intervalTime = 0.02f, keepingTime = 3f };
    [Tooltip("鸟瞰地图对象")]
    private GameObject brideyeMapObject;
    [Tooltip("鸟瞰地图中的ABC位置对象")]
    private GameObject brideyeABCObject;
    [Tooltip("鸟瞰地图中的玩家位置对象")]
    private GameObject brideyePlayerFlagObject;

    [Header("信息显示配置")]
    [Tooltip("P1成绩对象")]
    public GameObject P1ScoreObject;
    [Tooltip("P2成绩对象")]
    public GameObject P2ScoreObject;
    [Tooltip("P2成绩标签对象")]
    public GameObject P2ScoreLabelObject;
    [Tooltip("P1生命对象")]
    public GameObject P1LifeObject;
    [Tooltip("P2生命对象")]
    public GameObject P2LifeObject;
    [Tooltip("P2生命标签对象")]
    public GameObject P2LifeLabelObject;
    [Tooltip("关卡号对象")]
    public GameObject LevelNoObject;
    [Tooltip("关卡名对象")]
    public GameObject LevelNameObject;
    [Tooltip("最高成绩对象")]
    public GameObject HIScoreObject;


    [Header("关卡配置")]
    [Tooltip("关卡地图及标记的位置信息")]
    private LevelConfig[] levelsConfig = new LevelConfig[]
    {
        new (){
            levelName="第1关",
            PlayerFlagPosition=new Vector2(2.75f, 2.9375f),
            BrideyeMapPosition=new Vector2(1f, 10f),
            BrideyePlayerFlagPosition=new Vector2(3.25f, -2.75f),
            scrollBackLeftLimit=0f,
        },
        new (){
            levelName="第2关",
            PlayerFlagPosition = new Vector2(112f / 16f, 47f / 16f),
            BrideyeMapPosition = new Vector2(1f, 10f),
            BrideyePlayerFlagPosition = new Vector2(65f / 16f, -38f / 16f),
            scrollBackLeftLimit=0f,
        },
        new()
        {
            levelName="第3关",
            PlayerFlagPosition = new Vector2(160f / 16f, 47f / 16f),
            BrideyeMapPosition = new Vector2(1f, 10f),
            BrideyePlayerFlagPosition = new Vector2(61f / 16f, -35f / 16f),
            scrollBackLeftLimit=0f,
        },
        new()
        {
            levelName="第4关",
            PlayerFlagPosition = new Vector2(160f / 16f, 111f / 16f),
            BrideyeMapPosition = new Vector2(1f, 10f),
            BrideyePlayerFlagPosition = new Vector2(58f / 16f, -27f / 16f),
            scrollBackLeftLimit=0f,
        },
        new()
        {
            levelName="第5关",
            PlayerFlagPosition = new Vector2(200f / 16f, 112f / 16f),
            BrideyeMapPosition = new Vector2(1f, 10f),
            BrideyePlayerFlagPosition = new Vector2(52f / 16f, -27f / 16f),
            scrollBackLeftLimit=0f,
        },
        new()
        {
            levelName="第6关",
            PlayerFlagPosition = new Vector2(249f / 16f, 47f / 16f),
            BrideyeMapPosition = new Vector2(17f, 10f),
            BrideyePlayerFlagPosition = new Vector2(45f / 16f, -1.5f),
            scrollBackLeftLimit=9f,
            showUnderGroundIndex=1,
        },
        new()
        {
            levelName="第7关",
            PlayerFlagPosition = new Vector2(297f / 16f, 47f / 16f),
            BrideyeMapPosition = new Vector2(17f, 10f),
            BrideyePlayerFlagPosition = new Vector2(37 / 16f, -24f / 16f),
            scrollBackLeftLimit=9f,
            showUnderGroundIndex=2,
        },
        new()
        {
            levelName="第8关",
            PlayerFlagPosition = new Vector2(345f / 16f, 48f / 16f),
            BrideyeMapPosition = new Vector2(17f, 10f),
            BrideyePlayerFlagPosition = new Vector2(28f / 16f, -21f / 16f),
            scrollBackLeftLimit=9f,
            showUnderGroundIndex=3,
        },
    };
    [Tooltip("当前关卡信息")]
    private ContraGlobal.ContraLevel level;
    [Tooltip("当前关卡配置信息")]
    private LevelConfig levelConfig;

    [Header("操作状态")]
    [Tooltip("场景动作是否完成")]
    private bool scenarioDone = false;
    [Tooltip("Start键是否按下")]
    private bool startPress = false;


    private void Awake()
    {
        if (debug)
        {
            ContraGlobal.currentLevel = debugLevel - 1;
        }

        playerFlagObject = Utility.GetObjectWithName("玩家位置标记");
        brideyeMapObject = Utility.GetObjectWithName("俯视地图");
        brideyeABCObject = Utility.GetObjectWithName("俯视地图-ABC");
        brideyePlayerFlagObject = Utility.GetObjectWithName("俯视地图-玩家位置标记");
        (new GameObject[] { playerFlagObject, brideyeMapObject, brideyeABCObject, brideyePlayerFlagObject }).Action((GameObject o) =>
        {
            o.SetActive(false);
        });

        level = ContraGlobal.CurrentLevel();
        levelConfig = levelsConfig[ContraGlobal.currentLevel];
        {
            if (P1ScoreObject.TryGetComponent(out Text text))
            {
                text.text = string.Format("{0:D}", ContraGlobal.Player1.Score);
            }
        }
        {
            if (P1LifeObject.TryGetComponent(out Text text))
            {
                text.text = string.Format("{0:D}", ContraGlobal.Player1.Life);
            }

        }
        {
            if (HIScoreObject.TryGetComponent(out Text text))
            {
                text.text = string.Format("{0:D}", ContraGlobal.HIScroe);
            }
        }
        playerFlagObject.transform.localPosition = levelConfig.PlayerFlagPosition;
        brideyeMapObject.transform.localPosition = levelConfig.BrideyeMapPosition;
        brideyePlayerFlagObject.transform.localPosition = levelConfig.BrideyePlayerFlagPosition;

        if (ContraGlobal.IsTwoPlayers())
        {
            P2ScoreObject.SetActive(true);
            P2ScoreLabelObject.SetActive(true);
            P2LifeObject.SetActive(true);
            P2LifeLabelObject.SetActive(true);
            {
                if (P2ScoreObject.TryGetComponent(out Text text))
                {
                    text.text = string.Format("{0:D}", ContraGlobal.Player2.Score);
                }
            }
            {
                if (P2LifeObject.TryGetComponent(out Text text))
                {
                    text.text = string.Format("{0:D}", ContraGlobal.Player2.Life);
                }
            }
        }
        else
        {
            P2ScoreObject.SetActive(false);
            P2ScoreLabelObject.SetActive(false);
            P2LifeObject.SetActive(false);
            P2LifeLabelObject.SetActive(false);
        }

        {
            if (LevelNoObject.TryGetComponent(out Text text))
            {
                text.text = string.Format("{0:D}", ContraGlobal.currentLevel + 1);
            }
        }
        {
            if (LevelNameObject.TryGetComponent(out Text text))
            {
                text.text = string.Format("{0:G}", level.LevelName);
            }
        }

        for (int i = 0; i < underGroundObjects.Length; i++)
        {
            underGroundObjects[i].SetActive(false);
        }
    }
    private void Update()
    {
        startPress = Input.GetButtonDown("Start");
    }
    private void FixedUpdate()
    {
        UpdateScenario();
        if (startPress)
        {
            StartScene();
        }
    }

    private void UpdateScenario()
    {
        cameraMoveAction.Update((SeqAction seq) =>
        {
            if (seq.IsFirstAction())
            {
                warningSound.loop = true;
                warningSound.Play();
            }
            Vector3 position = transform.position;
            position += cameraMoveSpeed * seq.DeltaTime * cameraMoveDirection;
            if (position.x > cameraRightEdge)
            {
                position.x = cameraRightEdge;
            }
            else if (position.x < cameraLeftEdge)
            {
                position.x = cameraLeftEdge;
            }
            transform.position = position;
            if (position.x >= cameraRightEdge && cameraMoveDirection == Vector3.right)
            {
                position.x = cameraRightEdge;
                cameraMoveDirection = Vector3.left;
                cameraMoveAction.ReStart();
            }
            else if (position.x <= cameraLeftEdge + levelConfig.scrollBackLeftLimit && cameraMoveDirection == Vector3.left)
            {
                position.x = cameraLeftEdge + levelConfig.scrollBackLeftLimit;
                seq.done = true;
            }
        });

        if (cameraMoveAction.done)
        {
            brideyeMapScrollAction.Update((SeqAction seq) =>
            {
                if (seq.IsFirstAction())
                {
                    warningSound.Stop();
                    brideyeScrollSound.loop = false;
                    brideyeScrollSound.Play();
                }
                brideyeMapObject.SetActive(true);
                if (brideyeMapObject.TryGetComponent(out SpriteRenderer sr))
                {
                    Vector2 size = sr.size;
                    size.y -= brideyeMapScrollSpeed * seq.DurationTime;
                    if (size.y <= 0)
                    {
                        size.y = 0;
                        seq.done = true;
                    }
                    Transform maskTransofrm = brideyeMapObject.transform.Find("Mask");
                    Vector2 localScale = maskTransofrm.localScale;
                    localScale.y = size.y;
                    maskTransofrm.localScale = localScale;
                    maskTransofrm.localPosition = new(maskTransofrm.localPosition.x, size.y / 2 - sr.size.y);
                }

            });
        }

        if (brideyeMapScrollAction.done)
        {
            for (int i = 0; i < underGroundObjects.Length; i++)
            {
                if (i < levelConfig.showUnderGroundIndex)
                {
                    underGroundObjects[i].SetActive(true);
                }
                else
                {
                    underGroundObjects[i].SetActive(false);
                }
            }

            playerFlagFlashAction.Update((SeqAction seq) =>
            {
                if (seq.IsFirstAction())
                {
                    brideyeScrollSound.Stop();
                    playerFlagTickSound.loop = true;
                    playerFlagTickSound.Play();
                }
                playerFlagObject.SetActive(true);
                if (playerFlagObject.TryGetComponent(out SpriteRenderer sr))
                {
                    int showIndex = Utility.OscillateIndex(playerFlagSptites.Length, seq.seqNo);
                    sr.sprite = playerFlagSptites[showIndex];
                }

            });

            brideyePlayerFlagFlashAction.Update((SeqAction seq) =>
            {
                brideyePlayerFlagObject.SetActive(true);
                brideyeABCObject.SetActive(true);
                if (brideyePlayerFlagObject.TryGetComponent(out SpriteRenderer sr))
                {
                    int showIndex = Utility.OscillateIndex(brideyePlayerFlagSptites.Length, seq.seqNo);
                    sr.sprite = brideyePlayerFlagSptites[showIndex];
                }
            });
        }

        if (!scenarioDone)
        {
            scenarioDone = playerFlagFlashAction.done && brideyePlayerFlagFlashAction.done;
            if (scenarioDone)
            {
                StartScene();
            }
        }
    }

    private void StartScene()
    {
        SceneManager.LoadScene(level.SceneName, LoadSceneMode.Single);
    }
}
